﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UFSoft.UBF.Business;

namespace UFSoft.UBF.Cust.ClassView.MVC.Utils
{
    /// <summary>
    ///     异常帮助类
    /// </summary>
    public static class ExceptionHelper
    {
        /// <summary>
        ///     获取错误信息
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="isTop">顶层调用</param>
        /// <returns></returns>
        public static string GetExceptionMsg(Exception ex, bool isTop = true)
        {
            List<string> errList = new List<string>();
            if (ex is BusinessException)
            {
                BusinessException bex = ex as BusinessException;
                if (bex.InnerExceptions != null && bex.InnerExceptions.Count > 0)
                {
                    foreach (Exception iex in bex.InnerExceptions)
                    {
                        errList.Add(GetExceptionMsg(iex, false));
                    }
                }
            }
            else if (ex.InnerException != null)
            {
                errList.Add(GetExceptionMsg(ex.InnerException, false));
            }
            else
            {
                errList.Add(ex.Message);
            }

            string errMsg = string.Join(".", errList.ToArray());
            if (!isTop) return errMsg;
            //移除<a href></a>
            string hrefPattern =
                @"(?is)<a(?:(?!href=).)*href=(['""]?)(?<url>[^""\s>]*)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>";
            return Regex.Replace(errMsg, hrefPattern, string.Empty);
        }
    }
}